"""
pytest配置文件
包含测试用例的fixture和配置
"""
import pytest
import os
from typing import List, Dict

import requests

from utils.database_util import DatabaseUtil
from utils.request_util import Request, host
from utils.yaml_util import read_yaml
from utils.logger_util import logger
from utils.redis_util import RedisUtil

host
log = logger.getlog()
pre_key = 'VERIFICATION_CODE_'

@pytest.fixture(scope='function')
def get_activity_list(get_token):
    url=host+'activity/find-list'
    param={
        'currentPage': 1,
        'pageSize': 100
    }
    headers = {
        'Content-Type': 'application/json',
        'user_token': get_token,
    }
    r = Request().get(url, headers=headers, params=param)
    
    # 添加响应验证，防止空值错误
    response_data = r.json()
    if response_data.get('data') is None:
        # 如果没有数据，返回空列表
        yield []
    else:
        yield response_data['data']['records']


@pytest.fixture(scope='function')
def get_activity_detail_info(db_util):
    db_cli = db_util

    def get_info(activity_id):
        """
        根据活动ID查询活动详细信息，返回指定格式的数据

        Args:
            activity_id: 活动ID

        Returns:
            dict: 包含活动详细信息的字典，格式如下：
            {
                "data": {
                    "activityId": 1001,
                    "activityName": "新年抽奖活动",
                    "description": "欢迎参加2025年新年抽奖活动",
                    "valid": true,
                    "prizes": [...],
                    "users": [...]
                },
                "msg": ""
            }
        """
        if not activity_id:
            return {"data": None, "msg": "活动ID不能为空"}

        try:
            # 1. 查询活动基本信息
            activity_sql = """
                           SELECT id, activity_name, description, status, duration, create_user_id
                           FROM activity
                           WHERE id = :activity_id \
                           """
            activity_results = db_cli.execute_query(activity_sql, {"activity_id": activity_id})

            if not activity_results:
                return {"data": None, "msg": f"未找到活动ID为{activity_id}的活动"}

            activity = activity_results[0]

            # 2. 查询活动奖品关联信息
            activity_prize_sql = """
                                 SELECT activity_id, prize_id, prize_amount, prize_tiers, status
                                 FROM activity_prize
                                 WHERE activity_id = :activity_id \
                                 """
            activity_prize_results = db_cli.execute_query(activity_prize_sql, {"activity_id": activity_id})

            # 3. 查询活动用户关联信息
            activity_user_sql = """
                                SELECT activity_id, user_id, user_name, status
                                FROM activity_user
                                WHERE activity_id = :activity_id \
                                """
            activity_user_results = db_cli.execute_query(activity_user_sql, {"activity_id": activity_id})

            # 4. 查询奖品基本信息
            prizes = []
            if activity_prize_results:
                prize_ids = [str(ap['prize_id']) for ap in activity_prize_results]
                prize_ids_str = ','.join(prize_ids)

                prize_sql = f"""
                    SELECT id, name, image_url, price, description
                    FROM prize 
                    WHERE id IN ({prize_ids_str})
                """
                prize_results = db_cli.execute_query(prize_sql, {})

                # 创建奖品ID到奖品信息的映射
                prize_map = {prize['id']: prize for prize in prize_results}

                # 5. 整合奖品信息
                for ap in activity_prize_results:
                    prize_id = ap['prize_id']
                    prize_info = prize_map.get(prize_id, {})

                    # 映射奖品等级名称
                    tier_name_map = {
                        'FIRST_PRIZE': '一等奖',
                        'SECOND_PRIZE': '二等奖',
                        'THIRD_PRIZE': '三等奖'
                    }

                    prize_data = {
                        "prizeId": prize_id,
                        "name": prize_info.get('name', '没有查询到奖品名字'),
                        "imageUrl": prize_info.get('image_url', '/static.png'),
                        "price": float(prize_info.get('price', 0)),
                        "description": prize_info.get('description', ''),
                        "prizeTierName": tier_name_map.get(ap['prize_tiers'], ap['prize_tiers']),
                        "prizeAmount": int(ap['prize_amount']),
                        "valid": ap['status'] == 'INIT'
                    }
                    prizes.append(prize_data)

            # 6. 整合用户信息
            users = []
            for au in activity_user_results:
                user_data = {
                    "userId": au['user_id'],
                    "userName": au['user_name'],
                    "valid": au['status'] == 'INIT'
                }
                users.append(user_data)

            # 7. 构造返回数据
            result_data = {
                "activityId": activity['id'],
                "activityName": activity['activity_name'],
                "description": activity['description'],
                "valid": activity['status'] == 'RUNNING',
                "prizes": prizes,
                "users": users
            }

            return {"data": result_data, "msg": ""}

        except Exception as e:
            log.error(f"查询活动详细信息失败: {str(e)}")
            return {"data": None, "msg": f"查询失败: {str(e)}"}

    yield get_info

@pytest.fixture(scope="session")
def db_config():
    """
    会话级fixture：读取数据库配置
    支持环境变量配置，优先级：环境变量 > YAML配置文件
    整个测试会话期间只读取一次配置
    """
    try:
        # 优先从环境变量读取配置
        if all(os.getenv(key) for key in ['DB_USERNAME', 'DB_PASSWORD', 'DB_HOST', 'DB_PORT', 'DB_DATABASE']):
            config = {
                'username': os.getenv('DB_USERNAME'),
                'password': os.getenv('DB_PASSWORD'),
                'host': os.getenv('DB_HOST'),
                'port': int(os.getenv('DB_PORT')),
                'database': os.getenv('DB_DATABASE')
            }
            logger.getlog().info(f"使用环境变量数据库配置: {config['host']}:{config['port']}/{config['database']}")
        else:
            # 回退到YAML配置文件（可根据需要修改为test_config）
            config = read_yaml("db_config.yaml", "local_config")
            logger.getlog().info(f"使用YAML文件数据库配置: {config['host']}:{config['port']}/{config['database']}")

        return config
    except Exception as e:
        logger.getlog().error(f"数据库配置加载失败: {e}")
        raise


@pytest.fixture(scope="session")
def db_util(db_config):
    """
    会话级fixture：创建数据库工具实例
    整个测试会话期间复用同一个数据库连接
    """
    try:
        db = DatabaseUtil(
            username=db_config["username"],
            password=db_config["password"],
            host=db_config["host"],
            port=db_config["port"],
            database=db_config["database"]
        )
        logger.getlog().info("数据库连接创建成功")
        yield db
        # 测试会话结束时关闭连接
        db.close()
        logger.getlog().info("数据库连接已关闭")
    except Exception as e:
        logger.getlog().error(f"数据库连接创建失败: {e}")
        raise


@pytest.fixture(scope="function")
def redis_util():
    """
    函数级fixture：创建Redis工具实例
    每个测试函数都会创建新的Redis连接，测试结束后自动关闭
    使用环境变量配置Redis连接参数
    """
    redis_client = None
    try:
        # 使用环境变量配置创建Redis连接
        redis_client = RedisUtil()
        logger.getlog().info("Redis连接创建成功")
        yield redis_client
    except Exception as e:
        logger.getlog().error(f"Redis连接创建失败: {e}")
        raise
    finally:
        # 测试结束时关闭连接
        if redis_client:
            redis_client.flushall()
            redis_client.close()
            logger.getlog().info("Redis连接已关闭")


def _list_all_tables(db_util: DatabaseUtil, exclude_tables: List[str] = None) -> List[str]:
    """
    获取数据库中所有表名（排除系统表和指定排除表）
    
    Args:
        db_util: 数据库工具实例
        exclude_tables: 需要排除的表名列表
        
    Returns:
        表名列表
    """
    if exclude_tables is None:
        exclude_tables = []

    # 查询所有用户表（排除系统表）
    sql = """
          SELECT table_name
          FROM information_schema.tables
          WHERE table_schema = DATABASE()
            AND table_type = 'BASE TABLE' \
          """

    try:
        result = db_util.execute_query(sql)
        all_tables = [row['table_name'] for row in result]

        # 排除指定的表
        filtered_tables = [table for table in all_tables if table not in exclude_tables]

        logger.getlog().info(f"发现数据库表: {all_tables}")
        if exclude_tables:
            logger.getlog().info(f"排除表: {exclude_tables}")
        logger.getlog().info(f"待清理表: {filtered_tables}")

        return filtered_tables
    except Exception as e:
        logger.getlog().error(f"获取表列表失败: {e}")
        raise


@pytest.fixture(scope="function",autouse=False)
def purge_all_tables(db_util):
    """
    函数级fixture：测试用例执行后清空所有表数据
    
    使用方式：
    def test_something(purge_all_tables):
        # 测试代码...
        pass  # 测试结束后自动清空所有表
    
    注意：
    1. 仅在测试环境使用，生产环境禁用
    2. 会按外键依赖顺序清理表，避免外键约束错误
    3. 默认排除系统表，可通过EXCLUDE_TABLES环境变量自定义
    """
    # 前置操作：无需执行
    yield

    # 后置操作：清空所有表数据
    try:
        logger.getlog().info("开始执行数据库清库操作...")

        # 可配置的排除表列表（根据实际需要调整）
        exclude_tables = [
            # 'system_config',  # 系统配置表
            # 'dict_data',      # 字典数据表
        ]

        # 获取所有需要清理的表
        tables_to_clean = _list_all_tables(db_util, exclude_tables)

        if not tables_to_clean:
            logger.getlog().info("没有需要清理的表")
            return

        # 关闭外键检查，避免删除时的外键约束问题
        db_util.execute_update("SET FOREIGN_KEY_CHECKS = 0")

        # 按照外键依赖顺序清理表（子表 -> 父表）
        # 根据lottery_system.sql的表结构，建议的清理顺序：
        ordered_tables = [
            'user_activity',  # 用户活动关联表（如果存在）
            'user_prize',  # 用户奖品关联表（如果存在）
            'activity_prize',  # 活动奖品关联表
            'prize',  # 奖品表
            'activity',  # 活动表
            'user',  # 用户表
            'admin'  # 管理员表（如果存在）
        ]

        # 清理有序表
        for table in ordered_tables:
            if table in tables_to_clean:
                try:
                    affected_rows = db_util.execute_update(f"DELETE FROM {table}")
                    logger.getlog().info(f"清理表 {table}: 删除 {affected_rows} 行")
                except Exception as e:
                    logger.getlog().warning(f"清理表 {table} 失败: {e}")

        # 清理剩余表（不在有序列表中的表）
        remaining_tables = [t for t in tables_to_clean if t not in ordered_tables]
        for table in remaining_tables:
            try:
                affected_rows = db_util.execute_update(f"DELETE FROM {table}")
                logger.getlog().info(f"清理表 {table}: 删除 {affected_rows} 行")
            except Exception as e:
                logger.getlog().warning(f"清理表 {table} 失败: {e}")

        # 重新启用外键检查
        db_util.execute_update("SET FOREIGN_KEY_CHECKS = 1")

        logger.getlog().info("数据库清库操作完成")

    except Exception as e:
        logger.getlog().error(f"数据库清库操作失败: {e}")
        # 确保外键检查被重新启用
        try:
            db_util.execute_update("SET FOREIGN_KEY_CHECKS = 1")
        except:
            pass
        raise


@pytest.fixture(scope="function")
def purge_user_data(db_util):
    """
    函数级fixture：仅清理用户相关数据
    
    使用方式：
    def test_user_register(purge_user_data):
        # 测试用户注册...
        pass  # 测试结束后仅清理用户相关数据
    
    适用场景：
    - 用户相关的测试用例
    - 不需要清理全部数据的场景
    - 保留基础数据（如活动、奖品配置）的测试
    """
    # 前置操作：无需执行
    yield

    # 后置操作：清理用户相关数据
    try:
        logger.getlog().info("开始清理用户相关数据...")

        # 关闭外键检查
        db_util.execute_update("SET FOREIGN_KEY_CHECKS = 0")

        # 按依赖顺序清理用户相关表
        user_related_tables = [
            'user_activity',  # 用户活动关联（如果存在）
            'user_prize',  # 用户奖品关联（如果存在）
            'user'  # 用户表
        ]

        for table in user_related_tables:
            try:
                # 检查表是否存在
                check_sql = f"""
                SELECT COUNT(*) as count 
                FROM information_schema.tables 
                WHERE table_schema = DATABASE() 
                AND table_name = '{table}'
                """
                result = db_util.execute_query(check_sql)

                if result and result[0]['count'] > 0:
                    affected_rows = db_util.execute_update(f"DELETE FROM {table}")
                    logger.getlog().info(f"清理表 {table}: 删除 {affected_rows} 行")
                else:
                    logger.getlog().info(f"表 {table} 不存在，跳过清理")

            except Exception as e:
                logger.getlog().warning(f"清理表 {table} 失败: {e}")

        # 重新启用外键检查
        db_util.execute_update("SET FOREIGN_KEY_CHECKS = 1")

        logger.getlog().info("用户相关数据清理完成")

    except Exception as e:
        logger.getlog().error(f"用户数据清理失败: {e}")
        # 确保外键检查被重新启用
        try:
            db_util.execute_update("SET FOREIGN_KEY_CHECKS = 1")
        except:
            pass
        raise


# 注册接口的响应schema
@pytest.fixture(scope="function")
def register_response_schema():
    schema = \
        {
            "$schema": "http://json-schema.org/draft-07/schema#",
            "type": "object",
            "properties": {
                "code": {
                    "type": "integer"
                },
                "data": {
                    "type": "object",
                    "properties": {
                        "userId": {
                            "type": "integer"
                        }
                    },
                    "additionalProperties": False,
                    "required": [
                        "userId"
                    ]
                },
                "msg": {
                    "type": "string"
                }
            },
            "additionalProperties": False,
            "required": [
                "code",
                "data",
                "msg"
            ]
        }
    yield schema


#     自动注册一个用户
@pytest.fixture(scope="function")
def register_user():
    body = {
        "name": "张三",
        "mail": "zhangsan_test@example.com",
        "password": "Zha123456",
        "phoneNumber": "13800138009",
        "identity": "ADMIN",
        "loginName": "zhangsan_test@example.com"
    }
    response = None

    try:
        log.info(f"开始自动注册，body：{body}")
        response = Request().post(url=host + "register", json=body)
    except Exception as e:
        log.error(f"自动注册用户失败,host:{host},url:{host}register")
        log.error(f"错误信息：{response.json().get('msg')}")

    yield body


@pytest.fixture(scope="function")
def register_user_def(request):
    # 根据信息注册
    register_info: Dict[str, str] = request.param
    response = Request().post(url=host + "register", json=register_info)
    assert response.status_code == 200, '自定义注册失败'
    log.info(f"自定义注册响应结果：{response.json()}")
    yield register_info


# 返回密码登录的schema
@pytest.fixture(scope="function")
def login_schema():
    response = {
        "$schema": "http://json-schema.org/draft-07/schema#",
        "type": "object",
        "properties": {
            "code": {
                "type": "integer"
            },
            "data": {
                "type": "object",
                "properties": {
                    "token": {
                        "type": "string"
                    },
                    "identity": {
                        "type": "string"
                    }
                },
                "additionalProperties": False,
                "required": [
                    "token",
                    "identity"
                ]
            },
            "msg": {
                "type": "string"
            }
        },
        "additionalProperties": False,
        "required": [
            "code",
            "data",
            "msg"
        ]
    }
    yield response


# 检查令牌是否有效
def check_token(user_token):
    records_url = host + 'winning-records/show'
    body = {
        'activityId': 1001,
        'prizeId': 101
    }
    token_dir = {
        'user_token': user_token,
    }
    response = Request().post(url=records_url, json=body, headers=token_dir)
    assert response.status_code != 401, '鉴权必须通过'


# 令牌有效则 报错
def check_token_false(user_token):
    records_url = host + 'winning-records/show'
    body = {
        'activityId': 1001,
        'prizeId': 101
    }
    response = Request().post(url=records_url, json=body, headers=user_token)
    assert response.status_code == 401, 'token必须是无效的'


@pytest.fixture(scope="function")
def get_vericode(redis_util, register_user_def):
    after = 'verification-code/send'
    url = host + after
    mail = register_user_def['mail']
    r = Request().get(url=url, params={"phoneNumber": mail})
    redis_cli = redis_util
    code = redis_cli.get(pre_key + mail)
    assert code is not None
    yield code


@pytest.fixture(scope='function')
def get_token(register_user,purge_user_data):
   register_info: Dict[str, str] =register_user
   body={
       'loginName': register_info['mail'],
       'password': register_info['password'],
       'mandatoryIdentity': register_info['identity']
   }
   response=Request().post(url=host+'password/login',json=body)
   yield response.json()['data']['token']


@pytest.fixture(scope="function")
def register_seven_users():
    """
    函数级fixture：批量注册7个用户
    
    返回格式：
    [
        {
            'user_info': {...},  # 用户注册信息
            'token': '...',      # 用户登录令牌
            'user_id': 123       # 用户ID
        },
        ...
    ]
    
    使用方式：
    def test_multiple_users(register_seven_users):
        users = register_seven_users
        assert len(users) == 7
        # 使用 users[0]['token'] 获取第一个用户的令牌
        # 使用 users[0]['user_info'] 获取第一个用户的注册信息
    """
    users = []
    
    # 定义7个不同的用户信息
    user_templates = [
        {
            "name": "张山",
            "mail": "zhangsan_batch@example.com",
            "password": "Zha123456",
            "phoneNumber": "13800138001",
            "identity": "ADMIN",
            "loginName": "zhangsan_batch@example.com"
        },
        {
            "name": "李四",
            "mail": "lisi_batch@example.com",
            "password": "Lis123456",
            "phoneNumber": "13800138002",
            "identity": "NORMAL",
            "loginName": "lisi_batch@example.com"
        },
        {
            "name": "王五",
            "mail": "wangwu_batch@example.com",
            "password": "Wan123456",
            "phoneNumber": "13800138003",
            "identity": "NORMAL",
            "loginName": "wangwu_batch@example.com"
        },
        {
            "name": "赵六",
            "mail": "zhaoliu_batch@example.com",
            "password": "Zha123456",
            "phoneNumber": "13800138004",
            "identity": "NORMAL",
            "loginName": "zhaoliu_batch@example.com"
        },
        {
            "name": "孙七",
            "mail": "sunqi_batch@example.com",
            "password": "Sun123456",
            "phoneNumber": "13800138005",
            "identity": "ADMIN",
            "loginName": "sunqi_batch@example.com"
        },
        {
            "name": "周八",
            "mail": "zhouba_batch@example.com",
            "password": "Zho123456",
            "phoneNumber": "13800138006",
            "identity": "NORMAL",
            "loginName": "zhouba_batch@example.com"
        },
        {
            "name": "吴九",
            "mail": "wujiu_batch@example.com",
            "password": "Wu123456",
            "phoneNumber": "13800138007",
            "identity": "NORMAL",
            "loginName": "wujiu_batch@example.com"
        }
    ]
    
    try:
        for i, user_info in enumerate(user_templates):
            log.info(f"开始注册第{i+1}个用户：{user_info['name']}")
            
            # 注册用户
            register_response = Request().post(url=host + "register", json=user_info)
            register_response.raise_for_status()
            assert register_response.json().get('code') == 200, f'用户 {user_info["name"]} 注册失败'
            
            user_id = register_response.json().get('data', {}).get('userId')
            log.info(f"用户 {user_info['name']} 注册成功，用户ID：{user_id}")
            
            # 登录获取令牌
            login_body = {
                'loginName': user_info['mail'],
                'password': user_info['password'],
                'mandatoryIdentity': user_info['identity']
            }
            login_response = Request().post(url=host + 'password/login', json=login_body)
            login_response.raise_for_status()
            assert login_response.json().get('code') == 200, f'用户 {user_info["name"]} 登录失败'
            
            token = login_response.json().get('data', {}).get('token')
            log.info(f"用户 {user_info['name']} 登录成功，获取令牌")
            
            # 添加到用户列表
            users.append({
                'user_info': user_info,
                'token': token,
                'user_id': user_id
            })
            
        log.info(f"批量注册完成，成功注册 {len(users)} 个用户")
        yield users
        
    except Exception as e:
        log.error(f"批量注册用户失败：{e}")
        raise


@pytest.fixture(scope="function")
def create_three_prizes(get_token,get_latest_prize):
    """
    创建三个奖品的夹具
    
    使用picture-file目录中的前三个图片文件按原有顺序创建奖品
    使用get_token夹具获取认证令牌
    
    Returns:
        list: 包含三个奖品信息的列表，每个奖品包含：
            - prize_id: 奖品ID
            - prize_name: 奖品名称
            - description: 奖品描述
            - price: 奖品价格
            - image_file: 使用的图片文件名
    """
    import os
    import json
    from utils.request_util import Request, host
    
    # 获取认证令牌
    token = get_token
    
    # 获取picture-file目录路径
    picture_dir = os.path.join(os.path.dirname(__file__), 'picture-file')
    picture_dir = os.path.abspath(picture_dir)
    
    # 获取目录中的所有图片文件
    image_files = []
    for file in os.listdir(picture_dir):
        file_path = os.path.join(picture_dir, file)
        if os.path.isfile(file_path) and file.lower().endswith(('.png', '.jpg', '.jpeg')):
            image_files.append(file)
    
    # 按文件名排序，取前三个
    image_files.sort()
    selected_images = image_files[:3]
    
    # 预定义的三个奖品信息
    prizes_info = [
        {
            'prizeName': 'iPhone 15 Pro',
            'description': '苹果最新款手机',
            'price': 8999
        },
        {
            'prizeName': 'MacBook Pro',
            'description': '专业级笔记本电脑',
            'price': 15999
        },
        {
            'prizeName': 'AirPods Pro',
            'description': '无线降噪耳机',
            'price': 1999
        }
    ]
    
    created_prizes = []
    
    # 创建三个奖品
    for i, (image_file, prize_info) in enumerate(zip(selected_images, prizes_info)):
        try:
            image_path = os.path.join(picture_dir, image_file)
            
            logger.getlog().info(f"准备创建第{i+1}个奖品，使用图片: {image_file}")
            logger.getlog().info(f"奖品信息: {prize_info}")
            
            # 准备请求头
            headers = {
                'user_token': token
            }
            
            # 将奖品信息转换为JSON字符串
            param_json = json.dumps(prize_info)
            
            # 打开文件并发送请求
            with open(image_path, 'rb') as f:
                files = {
                    'param': (None, param_json, 'application/json'),
                    'prizePic': (image_file, f, 'image/png' if image_file.endswith('.png') else 'image/jpeg')
                }
                
                # 发送创建奖品请求
                response = Request().post(url=host + 'prize/create', files=files, headers=headers)
                
                # 响应校验
                if response and response.status_code == 200:
                    response_data = response.json()
                    if response_data.get('code') == 200:
                        prize_id = response_data.get('data')
                        get_prize_fun=get_latest_prize
                        prize_info_db=get_prize_fun()
                        created_prize = {
                            'prize_id': prize_info_db['id'],
                            'prize_name': prize_info_db['name'],
                            'description': prize_info_db['description'],
                            'price': prize_info_db['price'],
                            'image_file': prize_info_db['image_url']
                        }
                        created_prizes.append(created_prize)
                        logger.getlog().info(f"奖品创建成功，奖品ID: {prize_id}")
                    else:
                        logger.getlog().error(f"奖品创建失败，响应: {response_data}")
                        raise Exception(f"奖品创建失败: {response_data.get('msg', '未知错误')}")
                else:
                    logger.getlog().error(f"奖品创建请求失败，状态码: {response.status_code if response else 'None'}")
                    raise Exception(f"奖品创建请求失败")
                    
        except Exception as e:
            logger.getlog().error(f"创建第{i+1}个奖品时出现异常: {e}")
            raise
    
    logger.getlog().info(f"成功创建{len(created_prizes)}个奖品")
    return created_prizes


@pytest.fixture(scope="function")
def get_latest_prize(db_util):
    """
    查询数据库中最新奖品的夹具
    
    返回一个查询函数，测试用例可以在执行过程中调用该函数来获取最新奖品信息
    
    Args:
        db_util: 数据库工具实例
        
    Returns:
        function: 查询最新奖品的函数，调用该函数返回：
            dict: 最新奖品的完整信息，包含：
                - id: 奖品ID
                - gmt_create: 创建时间
                - gmt_modified: 修改时间
                - name: 奖品名称
                - description: 奖品描述
                - price: 奖品价格
                - image_url: 奖品图片地址
            如果没有奖品数据，返回 None
            
    使用示例:
        def test_example(get_latest_prize):
            query_func = get_latest_prize
            latest_prize = query_func()  # 调用函数获取最新奖品
            if latest_prize:
                print(f"奖品名称: {latest_prize['name']}")
    """
    def get_latest_prize_func():
        try:
            # 查询最新的奖品（按创建时间倒序）
            sql = """
            SELECT id, gmt_create, gmt_modified, name, description, price, image_url
            FROM prize 
            ORDER BY gmt_create DESC, id DESC 
            LIMIT 1
            """
            
            logger.getlog().info("开始查询数据库中最新的奖品")
            result = db_util.execute_query(sql)
            
            if result and len(result) > 0:
                latest_prize = result[0]
                logger.getlog().info(f"查询到最新奖品: ID={latest_prize['id']}, 名称={latest_prize['name']}")
                logger.getlog().info(f"奖品详情: {latest_prize}")
                return latest_prize
            else:
                logger.getlog().warning("数据库中没有找到任何奖品数据")
                return None
                
        except Exception as e:
            logger.getlog().error(f"查询最新奖品失败: {e}")
            raise
    
    yield get_latest_prize_func



